/**
 * 前端交互逻辑
 * 处理参数配置、API调用和结果可视化
 */

// API配置
const API_BASE = 'http://localhost:5000/api';

// 全局变量
let chart = null;
let statusInterval = null;

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeChart();
    bindEvents();
    updateStats();
});

// 事件绑定
function bindEvents() {
    // 码率滑块
    document.getElementById('codeRate').addEventListener('input', function(e) {
        document.getElementById('codeRateValue').textContent = e.target.value;
        updateStats();
    });
    
    // 其他参数变化
    ['codeLength', 'listSize'].forEach(id => {
        document.getElementById(id).addEventListener('change', updateStats);
    });
    
    // 按钮事件
    document.getElementById('startBtn').addEventListener('click', startSimulation);
    document.getElementById('stopBtn').addEventListener('click', stopSimulation);
}

// 更新统计信息
function updateStats() {
    const N = parseInt(document.getElementById('codeLength').value);
    const R = parseFloat(document.getElementById('codeRate').value);
    const L = parseInt(document.getElementById('listSize').value);
    const K = Math.floor(N * R);
    
    document.getElementById('statN').textContent = N;
    document.getElementById('statK').textContent = K;
    document.getElementById('statR').textContent = R.toFixed(2);
    document.getElementById('statL').textContent = L;
}

// 初始化图表
function initializeChart() {
    const ctx = document.getElementById('berChart').getContext('2d');
    
    chart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                label: 'BER',
                data: [],
                borderColor: 'rgb(34, 197, 94)',
                backgroundColor: 'rgba(34, 197, 94, 0.1)',
                borderWidth: 3,
                pointRadius: 4,
                pointBackgroundColor: 'rgb(34, 197, 94)',
                tension: 0.1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    labels: {
                        color: 'white',
                        font: {
                            size: 14
                        }
                    }
                },
                tooltip: {
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    titleColor: 'white',
                    bodyColor: 'white',
                    callbacks: {
                        label: function(context) {
                            return `BER: ${context.parsed.y.toExponential(2)}`;
                        }
                    }
                }
            },
            scales: {
                x: {
                    type: 'linear',
                    title: {
                        display: true,
                        text: 'SNR (dB)',
                        color: 'white',
                        font: {
                            size: 14
                        }
                    },
                    ticks: {
                        color: 'white'
                    },
                    grid: {
                        color: 'rgba(255, 255, 255, 0.1)'
                    }
                },
                y: {
                    type: 'logarithmic',
                    title: {
                        display: true,
                        text: 'Bit Error Rate (BER)',
                        color: 'white',
                        font: {
                            size: 14
                        }
                    },
                    ticks: {
                        color: 'white',
                        callback: function(value) {
                            return value.toExponential(1);
                        }
                    },
                    grid: {
                        color: 'rgba(255, 255, 255, 0.1)'
                    }
                }
            }
        }
    });
}

// 开始仿真
async function startSimulation() {
    const params = {
        N: parseInt(document.getElementById('codeLength').value),
        K: Math.floor(parseInt(document.getElementById('codeLength').value) * 
                     parseFloat(document.getElementById('codeRate').value)),
        L: parseInt(document.getElementById('listSize').value),
        snr_start: parseFloat(document.getElementById('snrStart').value),
        snr_end: parseFloat(document.getElementById('snrEnd').value),
        snr_step: parseFloat(document.getElementById('snrStep').value),
        num_trials: parseInt(document.getElementById('numTrials').value)
    };
    
    try {
        // 发送开始请求
        const response = await axios.post(`${API_BASE}/simulate`, params);
        
        if (response.status === 200) {
            // 更新UI状态
            document.getElementById('startBtn').disabled = true;
            document.getElementById('stopBtn').disabled = false;
            
            // 开始轮询状态
            startStatusPolling();
        }
    } catch (error) {
        showError('启动仿真失败: ' + error.message);
    }
}

// 停止仿真
async function stopSimulation() {
    try {
        await axios.post(`${API_BASE}/stop`);
        resetUI();
    } catch (error) {
        console.error('停止仿真失败:', error);
    }
}

// 轮询仿真状态
function startStatusPolling() {
    statusInterval = setInterval(async () => {
        try {
            const response = await axios.get(`${API_BASE}/status`);
            const status = response.data;
            
            // 更新进度
            updateProgress(status.progress);
            
            if (status.results) {
                // 仿真完成
                updateResults(status.results);
                resetUI();
                clearInterval(statusInterval);
            } else if (status.error) {
                // 仿真错误
                showError(status.error);
                resetUI();
                clearInterval(statusInterval);
            } else if (!status.running) {
                // 仿真停止
                resetUI();
                clearInterval(statusInterval);
            }
        } catch (error) {
            console.error('获取状态失败:', error);
        }
    }, 1000);
}

// 更新进度
function updateProgress(progress) {
    document.getElementById('progressBar').style.width = progress + '%';
    document.getElementById('progressText').textContent = progress + '%';
}

// 更新结果
function updateResults(results) {
    // 更新图表
    chart.data.labels = results.snr_db;
    chart.data.datasets[0].data = results.ber.map((ber, i) => ({
        x: results.snr_db[i],
        y: ber
    }));
    chart.update();
    
    // 更新表格
    const tbody = document.getElementById('resultsTable');
    tbody.innerHTML = '';
    
    results.snr_db.forEach((snr, i) => {
        const row = tbody.insertRow();
        row.insertCell(0).textContent = snr.toFixed(1);
        row.insertCell(1).textContent = results.ber[i].toExponential(2);
    });
}

// 重置UI
function resetUI() {
    document.getElementById('startBtn').disabled = false;
    document.getElementById('stopBtn').disabled = true;
    updateProgress(0);
}

// 显示错误
function showError(message) {
    alert(message);
}

// 测试API连接
async function testConnection() {
    try {
        const response = await axios.get(`${API_BASE}/test`);
        console.log('API连接成功:', response.data);
    } catch (error) {
        console.error('API连接失败:', error);
    }
}

// 页面加载时测试连接
testConnection();
